package com.aivin.lib_readnotes.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.aivin.lib_base.tool.MyDeviceInforHelper;
import com.aivin.lib_base.tool.RouteUtils;
import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_reader.TurnStatus;
import com.aivin.lib_reader.icallback.MenuLayCallBack;
import com.aivin.lib_reader.icallback.PageChangedCallback;
import com.aivin.lib_reader.icallback.SettingViewCallBack;
import com.aivin.lib_reader.tool.ReaderManager;
import com.aivin.lib_reader.tool.ReaderResolve;
import com.aivin.lib_reader.view.ReaderBottomLay;
import com.aivin.lib_reader.view.ReaderView;
import com.aivin.lib_reader.view.SettingView;
import com.aivin.lib_readnotes.R;
import com.aivin.lib_readnotes.adapter.CatalogueAdapter;
import com.aivin.lib_widget.base.BaseActivity;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.navigation.NavigationView;
import com.gyf.immersionbar.ImmersionBar;
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView;
import com.tencent.mmkv.MMKV;

import io.reactivex.Observable;
import com.aivin.lib_base.spiders.ChapterSpider;
import com.aivin.lib_base.spiders.ISpiderCallBack;
import com.aivin.lib_base.tool.RxjavaTool;
import com.aivin.lib_base.spiders.SpiderTool;
import java.util.List;

/**
 * 纯文本阅读器
 */
@Route(path = RouteUtils.PureTextReaderActivity)
public class PureTextReaderActivity extends BaseActivity {
    private ReaderView mReaderView;
    private ReaderManager mReaderManager;
    private ReaderBottomLay mReaderBottomLay;
    private SettingView mSettingView;
    private DrawerLayout mDrawerLayout;//操作抽屉
    private NavigationView mNavigationView;//左侧用于展示目录的抽屉
    private FastScrollRecyclerView mRecyclerView;
    private SpiderTool spiderTool = new SpiderTool() ;
    private MMKV mmkv = MMKV.defaultMMKV();
    private String bookUrl;
    private Context mContext ;
    private TextView loadErrorInfoTv ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_extend_reader);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarColor( R.color.color_fff)
                .init();

        mContext =this ;
        initReader();
        initView();
        initData();
    }

    private void initView() {
        loadErrorInfoTv = findViewById(R.id.loadErrorInfoTv);
        mReaderBottomLay = findViewById(R.id.menu_view);
        mReaderBottomLay.setMenuLayCallBack(menuLayCallBack);

        mSettingView = findViewById(R.id.setting_view);
        mSettingView.setSettingViewCallBack(settingViewCallBack);

        mDrawerLayout = findViewById(R.id.drawerLayout);
        mNavigationView = findViewById(R.id.navigation);
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));


        loadErrorInfoTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(bookUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        bookUrl = getIntent().getStringExtra("bookUrl") ;
        spiderTool.getChapters(bookUrl ,iSpiderCallBack);
    }

    private ISpiderCallBack iSpiderCallBack = new ISpiderCallBack() {
        @Override
        public void onStartLoad() {
            showLoadDialog2(mContext);
        }

        @SuppressLint("CheckResult")
        @Override
        public void onGetChapters(List<ChapterSpider> chapterSpiderList) {
            hideLoadDialog2();

            if(chapterSpiderList != null && chapterSpiderList.size()>0 )   {
                Observable.just( chapterSpiderList)
                        .compose(RxjavaTool::toSimpleObservable)
                        .subscribe(value ->    {
                            loadErrorInfoTv.setVisibility(View.INVISIBLE);
                            updateChapters(value) ;
                        }) ;
            }
        }


        @SuppressLint("CheckResult")
        @Override
        public void onGetContent(String content) {
            hideLoadDialog2();

            Observable.just( content)
                    .compose(RxjavaTool::toSimpleObservable)
                    .subscribe(value ->    {
                        if(mReaderManager!=null){
                            loadErrorInfoTv.setVisibility(View.INVISIBLE);
                            mReaderManager.setContent(value);
                        }
                    }) ;
        }

        @SuppressLint("CheckResult")
        @Override
        public void onError(String error) {
            hideLoadDialog2();

            Observable.just( error)
                    .compose(RxjavaTool::toSimpleObservable)
                    .subscribe(value ->    {
                        loadErrorInfoTv.setVisibility(View.VISIBLE);
                        loadErrorInfoTv.setText(value);
                    }) ;
        }
    };

    private void updateChapters(  List<ChapterSpider> list){
        mReaderManager.setChapterList(list);
        mReaderManager.notifyDataSetChanged();
        mReaderBottomLay.setChapterSeekbar(list.size() - 1);

        CatalogueAdapter mCatalogueAdapter = new CatalogueAdapter(new CatalogueAdapter.OnItemClickListener() {
            @Override
            public void onIntemClick(int position) {
                TurnStatus turnStatus = mReaderManager.toSpecifiedChapter(position, ReaderResolve.FIRST_INDEX );
                if (turnStatus == TurnStatus.LOAD_SUCCESS) {
                    mReaderView.invalidateBothPage();
                }
                mDrawerLayout.closeDrawer(mNavigationView);

            }
        });

        mCatalogueAdapter.setList(list);
        mRecyclerView.setAdapter(mCatalogueAdapter);
        scrollToPosition();
    }

    private void initReader() {
        mReaderView = findViewById(R.id.extend_reader);
        mReaderManager = new ReaderManager(  spiderTool ,iSpiderCallBack);
        mReaderView.setReaderManager(mReaderManager);
        mReaderView.setBackgroundColor(getResources().getColor(R.color.reader_bg_2)); // 默认阅读背景
        mReaderView.setPageChangedCallback(new PageChangedCallback() {
            @Override
            public TurnStatus toPrevPage() {
                TurnStatus turnStatus = mReaderManager.toPrevPage();
                if (turnStatus == TurnStatus.NO_PREV_CHAPTER) {
                    shomsg(getString(R.string.str_noPrePage) ) ;
                }
                return turnStatus;
            }

            @Override
            public TurnStatus toNextPage() {
                TurnStatus turnStatus = mReaderManager.toNextPage();
                if (turnStatus == TurnStatus.NO_NEXT_CHAPTER) {
                    shomsg(getString(R.string.str_noNextPage) ) ;
                }
                return turnStatus;
            }
        });
    }


    private MenuLayCallBack menuLayCallBack = new MenuLayCallBack() {
        @Override
        public void onOpenCatalogue(boolean isOpen) {
            mDrawerLayout.openDrawer(mNavigationView);
            mReaderBottomLay.dismiss();
        }

        @Override
        public void on2NextChapter() {
            TurnStatus turnStatus2 = mReaderManager.toNextChapter();
            if (turnStatus2 == TurnStatus.LOAD_SUCCESS) {
                mReaderView.invalidateBothPage();
                mReaderBottomLay.updateChapterSeekbar(true);
            } else if (turnStatus2 == TurnStatus.DOWNLOADING) {
                mReaderBottomLay.updateChapterSeekbar(true);
            } else if (turnStatus2 == TurnStatus.NO_NEXT_CHAPTER) {
                shomsg(getString(R.string.str_noNextChapter) );
            }
        }

        @Override
        public void on2PreChapter() {
            TurnStatus turnStatus = mReaderManager.toPrevChapter();
            if (turnStatus == TurnStatus.LOAD_SUCCESS) {
                mReaderView.invalidateBothPage();
                mReaderBottomLay.updateChapterSeekbar(false);
            } else if (turnStatus == TurnStatus.DOWNLOADING) {
                mReaderBottomLay.updateChapterSeekbar(false);
            } else if (turnStatus == TurnStatus.NO_PREV_CHAPTER) {
                shomsg(getString(R.string.str_noPreChapter));
            }
        }

        @Override
        public void onOpenSettingView(boolean isOpen) {
            mSettingView.show();
        }

        @Override
        public void onChangeChapterSeekBar(int progress) {
            TurnStatus turnStatus = mReaderManager.toSpecifiedChapter(progress, ReaderResolve.FIRST_INDEX);
            if (turnStatus == TurnStatus.LOAD_SUCCESS){
                mReaderView.invalidateBothPage();
            }

        }
    };


    private void shomsg(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    private SettingViewCallBack settingViewCallBack = new SettingViewCallBack() {
        @Override
        public void onChangeBgColor(int color) {
            mReaderView.setBackgroundColor(color);
        }

        @Override
        public void onChangeTextSize(int size) {
            mReaderView.setTextSize(size);
        }

        @Override
        public void onChangeLineSpage(int space) {
            mReaderView.setLineSpace(space);
        }
    };


    private long mDownTime;
    private float mDownX;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                int screenWidth = MyDeviceInforHelper.getScreenWidth(this);
                boolean isInArea =  ev.getX() > screenWidth / 3 && ev.getX() < screenWidth * 2 / 3;
                mDownTime = isInArea ?  System.currentTimeMillis() : 0 ;
                mDownX = ev.getX();
                break;

            case MotionEvent.ACTION_UP:
                int longClickTime = ViewConfiguration.getLongPressTimeout();// 系统默认的长按时间
                int touchSlop = ViewConfiguration.get(this).getScaledPagingTouchSlop(); // 系统默认的 移动的最小触发值

                boolean isClick = System.currentTimeMillis() - mDownTime < longClickTime && (Math.abs(ev.getX() - mDownX) < touchSlop);
                if (isClick) {
                    if(mDrawerLayout.isDrawerOpen(GravityCompat.START )){
                        mDrawerLayout.closeDrawer(GravityCompat.START );
                        return true;
                    }

                    if(mSettingView.isShowing()){
                        mSettingView.dismiss();
                        return true ;
                    }

                    if(mReaderBottomLay.isShowing()){
                        mReaderBottomLay.dismiss();
                        return true;
                    }

                    mReaderBottomLay.show();
                    return true;
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(mNavigationView)) {
            mDrawerLayout.closeDrawer(mNavigationView);
        } else if (mSettingView.isShowing()) {
            mSettingView.dismiss();
        } else if (mReaderBottomLay.isShowing()) {
            mReaderBottomLay.dismiss();
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void finish() {
        super.finish();
        getPositionAndOffset();
    }


    private void getPositionAndOffset() {
        mmkv.encode(bookUrl+"_lastChapterIndex", mReaderManager.getCurrentChapterIndex());
        mmkv.encode(bookUrl+"lastCharIndex", mReaderManager.getCurrentChapterIndex());
    }


    /**
     *  跳转到上次指定的地方
     */
    private void scrollToPosition() {
        int lastChapterIndex = mmkv.decodeInt(bookUrl+"_lastChapterIndex");
        int lastCharIndex = mmkv.decodeInt(bookUrl+"_lastCharIndex");
        if(mRecyclerView.getLayoutManager() != null && lastChapterIndex >= 0) {
            ((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(lastChapterIndex, 0);
        }

        TurnStatus turnStatus = mReaderManager.toSpecifiedChapter(lastChapterIndex, lastCharIndex);
        if (turnStatus == TurnStatus.LOAD_SUCCESS) {
            mReaderView.invalidateBothPage();
        }
    }
}
